﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ExcelTest
{
    public class ExcelHelper2
    {
        public static async Task ListToExcelAsync<T>(List<T> list, ExportModel model)
        {
            IWorkbook workbook = model.ExcelSuffix switch
            {
                ExcelSuffix.xlsx => new XSSFWorkbook(),
                ExcelSuffix.xls => new HSSFWorkbook(),
                _ => throw new ArgumentException(nameof(ExcelSuffix))
            };
            ISheet sheet = string.IsNullOrWhiteSpace(model.SheetName) ?
                workbook.CreateSheet("Sheet1") : workbook.CreateSheet(model.SheetName);

            //标题行
            IRow titleRow = sheet.CreateRow(0);
            Type type = typeof(T);
            for (int i = 0; i < type.GetProperties().Length; i++)
            {
                PropertyInfo property = type.GetProperties()[i];
                ExcelColumAttribute? excelColum = property.GetCustomAttribute<ExcelColumAttribute>();
                if (excelColum != null && excelColum.Ignore)
                    continue;
                ICell cell = titleRow.CreateCell(i);
                var columName = property.GetCustomAttribute<ExcelColumAttribute>()?.Name ?? property.Name;
                cell.SetCellValue(columName);
            }

            //数据
            for (int r = 0; r < list.Count; r++)
            {
                IRow row = sheet.CreateRow(r + 1);
                for (int c = 0; c < type.GetProperties().Length; c++)
                {
                    PropertyInfo property = type.GetProperties()[c];
                    ExcelColumAttribute? excelColum = property.GetCustomAttribute<ExcelColumAttribute>();
                    if (excelColum != null && excelColum.Ignore)
                        continue;
                    ICell cell = row.CreateCell(c);
                    cell.SetCellValue(property.GetValue(list[r])?.ToString() ?? "");
                }
            }

            //转为字节数组
            using MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();
            //保存为Excel文件
            using FileStream fileStream = new FileStream(model.FilePath, FileMode.Create, FileAccess.Write);
            await fileStream.WriteAsync(buf, 0, buf.Length);
            await fileStream.FlushAsync();
        }
    }
}
